package com.knight.tomcat.common;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class RunClass implements Runnable {
    private Socket socket;

    public RunClass(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
            KnightRequest request = new KnightRequest(inputStream);
            KnightResponse response = new KnightResponse(outputStream);
            String url = request.getUrl();
            AbstractServlet servlet = BootStrap.servletMapping.get(url);
            servlet.service(request, response);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
